package cn.zhengzhou.springbootmybatis.config;


import cn.zhengzhou.springbootmybatis.pojo.ResultVo;
import cn.zhengzhou.springbootmybatis.utils.JwtUtil;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        ResultVo<Object> resultVo = new ResultVo<>();
        // 获取令牌请求头
        String token = request.getHeader("token");
        if(token == null||token.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        System.out.println(token);
        try {
            jwtUtil.verifyToken(token);

            return true;
        }catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg", "无效签名!");
            resultVo.setMsg("无效签名!");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("msg", "token过期!");
            resultVo.setMsg("token过期!");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("msg", "token算法不一致!");
            resultVo.setMsg("token算法不一致!");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "token无效!!");
            resultVo.setMsg("token无效!!");
        }

        //设置状态
        map.put("state", false);
        resultVo.setCode(500);
        //将map转为json
        String json = new ObjectMapper().writeValueAsString(resultVo);
        // 相应json数据
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
